Practical-10
Mobile Application
Practical List
Create an android application to read a file from the sdcard and display that file content on the screen.
Steps
- Create a new Android project in Android Studio.
- Open the
activity_main.xmllayout file. - Add a
Buttonelement to the layout with the following attributes:android:id="@+id/button"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Read File"android:layout_gravity="center"
- Open the
MainActivity.javafile. - Inside the
onCreatemethod, add the following code to set the content view to theactivity_main.xmllayout:setContentView(R.layout.activity_main); - Create a new method called
readFileto handle the button click event and read the file content:private void readFile() {
File file = new File(Environment.getExternalStorageDirectory(), "file.txt");
StringBuilder content = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
TextView textView = findViewById(R.id.textView);
textView.setText(content.toString());
} - Run the application on an Android device or emulator.
- Click the "Read File" button to read the file content and display it on the screen.